package com.computergames.server.service.matcher;

import com.computergames.server.domain.MatchingPlayer;
import com.computergames.server.domain.MatchingType;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Matcher {
    private final ConcurrentLinkedQueue<MatchingPlayer> queue;
    private final MatchingType type;
    private final ExecutorService executor;

    public Matcher(MatchingType type, int threadCount) {
        this.queue = new ConcurrentLinkedQueue<>();
        this.type = type;
        this.executor = Executors.newFixedThreadPool(threadCount);
        this.executor.submit(this::matchPlayersLoop);
        Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));
    }
    public void addPlayer(MatchingPlayer player) {
        if (player.getMatchingType() == type) {
            queue.add(player);
        }
    }

    private void matchPlayersLoop() {
        while (true) {
            matchPlayers();
            try {
                Thread.sleep(1000); // 休眠一秒，模拟持续匹配
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
    }
    private void matchPlayers() {
        // 简化的匹配逻辑，实际应用中可能需要更复杂的算法
        while (!queue.isEmpty()) {
            MatchingPlayer player1 = queue.poll();
            if (player1 != null) {
                executor.execute(() -> {
                    MatchingPlayer player2 = findMatch(player1);
                    if (player2 != null) {
                        // 匹配成功，通知玩家
                        System.out.println("Matched players: " + player1.getUserId() + " and " + player2.getUserId());
                    }
                });
            }
        }
    }
    private MatchingPlayer findMatch(MatchingPlayer player) {
        // 简化的匹配逻辑，例如寻找等级相近的玩家
        return queue.stream()
                .filter(p -> Math.abs(p.getRating() - player.getRating()) <= 100)
                .findFirst()
                .orElse(null);
    }

    public void shutdown() {
        executor.shutdown();
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
